<template>
  <div class="modal-overlay" v-if="props.showFollowModal" @click="closeModal">
    <div class="modal-content" @click.stop>
      <!-- Tab切换 -->
      <div class="tab-container">
        <div
          :class="props.followType === 'follow' ? 'base_active_tab_item' : 'base_tab_item'"
          @click="switchTab('follow')">
          <span>Follow</span>
          <span>({{ formatNumber(props.followCount) }})</span>
        </div>
        <div
          :class="props.followType === 'fans' ? 'base_active_tab_item' : 'base_tab_item'"
          @click="switchTab('fans')">
          <span>Fans</span>
          <span>({{ formatNumber(props.fansCount) }})</span>
        </div>
      </div>

      <!-- 用户列表 -->
      <div class="user-list" ref="userListRef">
        <div v-if="loading" class="loading-container">
          <div class="loading-spinner"></div>
          <span>Loading...</span>
        </div>

        <div v-else-if="filteredUsers.length === 0" class="empty-state">
          <img src="@/assets/noData.webp" class="w-[64px]" alt="no more fans" />
          <div class="empty-text">
            {{
              props.followType === 'follow'
                ? 'No one is following you yet'
                : "You haven't followed anyone yet"
            }}
          </div>
        </div>

        <div v-else class="user-items">
          <div v-for="user in filteredUsers" :key="user.uid" class="user-item">
            <div class="user-avatar">
              <img :src="user.avatar" @click="handleUserClick(user.uid)" :alt="user.name" />
            </div>
            <div class="user-info">
              <div class="user-name">{{ user.name }}</div>
            </div>
            <div class="user-actions">
              <div
                v-if="[1, 2].includes(user.follow_flag)"
                class="base_button_ing"
                v-hover-bg="{
                  enterColor: '#F9D9C7',
                  leaveColor: '#fbe6db',
                }"
                :disabled="buttonLoading[user.uid]"
                @click="unfollowUser(user.uid)">
                <span v-if="buttonLoading[user.uid]" class="button-loading">
                  <div class="mini-spinner"></div>
                </span>
                <span v-else>
                  {{ user?.follow_flag === 1 ? 'Following' : 'Friends' }}
                </span>
              </div>
              <div
                v-hover-bg
                v-else
                class="base_button"
                :disabled="buttonLoading[user.uid]"
                @click="followUser(user.uid)">
                <span v-if="buttonLoading[user.uid]" class="button-loading">
                  <div class="mini-spinner"></div>
                </span>
                <span v-else>Follow</span>
              </div>
            </div>
          </div>

          <!-- 触底加载更多 -->
          <div v-if="loadMoreLoading" class="load-more-container">
            <div class="loading-spinner"></div>
            <span>Loading more...</span>
          </div>

          <!-- 没有更多数据提示 -->
          <div
            v-else-if="!hasMoreFollow && props.followType === 'follow' && followUsers.length > 0"
            class="no-more-container">
            <div class="no-more-text">-- No more --</div>
          </div>

          <div
            v-else-if="!hasMoreFans && props.followType === 'fans' && fansUsers.length > 0"
            class="no-more-container">
            -- No more --
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';
  import { UserAPI } from '@/api/user';
  import { useUserStore } from '@/store/user';
  import { useRouter } from 'vue-router';

  // 定义用户接口
  interface User {
    uid: number;
    name: string;
    avatar: string;
    followers: number;
    follow_flag: number;
  }

  // Props
  const props = defineProps<{
    showFollowModal: boolean;
    followCount: number;
    fansCount: number;
    uid: number | string;
    followType: 'follow' | 'fans' | null;
  }>();

  // Emits
  const emit = defineEmits<{
    close: [];
    updateFollowCount: [count: number];
    updateFansCount: [count: number];
    updateDataCount: [];
    followTypeChange: [type: 'follow' | 'fans' | null];
  }>();

  const userStore = useUserStore();
  const userInfo = userStore.user;

  const router = useRouter();

  // 响应式数据
  // const activeTab = ref<'follow' | 'fans'>(props.followType);
  const searchText = ref('');
  const filterType = ref<'all' | 'mutual' | 'recent'>('all');
  const loading = ref(false);
  const loadMoreLoading = ref(false);

  // 分页相关数据
  const followStart = ref(0);
  const fansStart = ref(0);
  const hasMoreFollow = ref(true);
  const hasMoreFans = ref(true);

  // 用户数据
  const followUsers = ref<User[]>([]);
  const fansUsers = ref<User[]>([]);

  // 按钮加载状态
  const buttonLoading = ref<{ [key: number]: boolean }>({});

  // 用户列表容器引用
  const userListRef = ref<HTMLElement | null>(null);

  // 添加滚动监听
  const addScrollListener = () => {
    nextTick(() => {
      if (userListRef.value) {
        userListRef.value.addEventListener('scroll', handleScroll);
        console.log('滚动监听已添加');
      }
    });
  };

  // 移除滚动监听
  const removeScrollListener = () => {
    if (userListRef.value) {
      userListRef.value.removeEventListener('scroll', handleScroll);
      console.log('滚动监听已移除');
    }
  };

  // 计算属性
  const currentUsers = computed(() => {
    return props.followType === 'follow' ? followUsers.value : fansUsers.value;
  });

  const filteredUsers = computed(() => {
    let users = currentUsers.value;

    // 搜索过滤
    if (searchText.value) {
      users = users.filter((user) =>
        user.name.toLowerCase().includes(searchText.value.toLowerCase())
      );
    }

    // 类型过滤
    if (filterType.value === 'mutual') {
      users = users.filter((user) => user.follow_flag);
    } else if (filterType.value === 'recent') {
      // 这里可以根据实际需求添加最近关注逻辑
      users = users.slice(0, 5);
    }

    return users;
  });

  // 数值格式化函数
  const formatNumber = (num: number): string => {
    if (!num) return '0';
    if (num >= 1000000) {
      return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'k';
    } else {
      return num.toString();
    }
  };

  // 数据加载方法
  const loadFollowings = async (isLoadMore = false) => {
    if (!userInfo?.uid) return;

    try {
      if (isLoadMore) {
        loadMoreLoading.value = true;
      } else {
        loading.value = true;
      }

      const params = {
        t_uid: props.uid,
        start: followStart.value,
        size: 20,
      };

      const response = await UserAPI.getFollowings(params);
      console.log(response, 'response====');

      const newUsers = response.data?.users || [];

      if (isLoadMore) {
        followUsers.value = [...followUsers.value, ...newUsers];
      } else {
        followUsers.value = newUsers;
      }

      // 更新分页信息
      followStart.value = response.data?.next_start || followUsers.value.length;
      hasMoreFollow.value = response.data?.has_more || false;

      console.log('加载关注列表成功:', response);
    } catch (error) {
      console.error('加载关注列表失败:', error);
    } finally {
      loading.value = false;
      loadMoreLoading.value = false;
    }
  };

  const loadFans = async (isLoadMore = false) => {
    if (!userInfo?.uid) return;

    try {
      if (isLoadMore) {
        loadMoreLoading.value = true;
      } else {
        loading.value = true;
      }

      const params = {
        t_uid: props.uid,
        start: fansStart.value,
        size: 20,
      };

      const response = await UserAPI.getFans(params);
      const newUsers = response.data?.users || [];

      if (isLoadMore) {
        fansUsers.value = [...fansUsers.value, ...newUsers];
      } else {
        fansUsers.value = newUsers;
      }

      // 更新分页信息
      fansStart.value = response.data?.next_start || fansUsers.value.length;
      hasMoreFans.value = response.data?.has_more || false;

      console.log('加载粉丝列表成功:', response);
    } catch (error) {
      console.error('加载粉丝列表失败:', error);
    } finally {
      loading.value = false;
      loadMoreLoading.value = false;
    }
  };

  // 触底加载更多数据
  const loadMore = async () => {
    if (loadMoreLoading.value) return;

    if (props.followType === 'follow' && hasMoreFollow.value) {
      await loadFollowings(true);
    } else if (props.followType === 'fans' && hasMoreFans.value) {
      await loadFans(true);
    }
  };

  // 滚动监听函数
  const handleScroll = (event: Event) => {
    const target = event.target as HTMLElement;
    const scrollTop = target.scrollTop;
    const scrollHeight = target.scrollHeight;
    const clientHeight = target.clientHeight;

    console.log('滚动信息:', {
      scrollTop,
      scrollHeight,
      clientHeight,
      distance: scrollHeight - (scrollTop + clientHeight),
      activeTab: props.followType,
      hasMoreFollow: hasMoreFollow.value,
      hasMoreFans: hasMoreFans.value,
    });

    // 当滚动到距离底部100px时触发加载
    if (scrollTop + clientHeight >= scrollHeight - 100) {
      console.log('触发加载更多');
      loadMore();
    }
  };

  // 方法
  const closeModal = () => {
    emit('close');
  };

  const refresh = () => {
    searchText.value = '';
    filterType.value = 'all';
    if (props.followType === 'follow') {
      loadFollowings();
    } else if (props.followType === 'fans') {
      loadFans();
    }
  };

  const switchTab = (tab: 'follow' | 'fans' | null) => {
    emit('followTypeChange', tab);
  };

  // 监听followType变化，同步更新activeTab
  watch(
    () => props.followType,
    (newType) => {
      refresh();
    },
    { deep: true, immediate: true }
  );

  const handleUserClick = (userId: number) => {
    router.push({ path: '/profile', query: { uid: userId } });
    closeModal();
  };

  const followUser = async (userId: number) => {
    // 设置按钮加载状态
    buttonLoading.value[userId] = true;

    try {
      const params = { to_id: userId };
      const response = await UserAPI.followUser(params);

      // 更新本地状态
      const user = currentUsers.value.find((u) => u.uid === userId);
      if (user) {
        user.follow_flag = 1;
      }

      emit('updateDataCount');

      console.log('关注用户成功:', response);
    } catch (error) {
      console.error('关注用户失败:', error);
      // 这里可以添加错误提示，比如使用Element Plus的Message组件
    } finally {
      // 清除按钮加载状态
      buttonLoading.value[userId] = false;
    }
  };

  const unfollowUser = async (userId: number) => {
    // 设置按钮加载状态
    buttonLoading.value[userId] = true;

    try {
      const params = { to_id: userId };
      const response = await UserAPI.unfollowUser(params);

      // 更新本地状态
      const user = currentUsers.value.find((u) => u.uid === userId);
      if (user) {
        user.follow_flag = 0;
      }

      emit('updateDataCount');

      console.log('取消关注用户成功:', response);
    } catch (error) {
      console.error('取消关注用户失败:', error);
      // 这里可以添加错误提示，比如使用Element Plus的Message组件
    } finally {
      // 清除按钮加载状态
      buttonLoading.value[userId] = false;
    }
  };

  console.log(123344);

  // 监听弹窗显示状态
  // watch(
  //   () => props.showFollowModal,
  //   (newValue) => {
  //     if (newValue) {
  //       // 弹窗显示时添加滚动监听
  //       addScrollListener();
  //       // 初始加载关注列表
  //       if (props.followType === 'follow') {
  //         loadFollowings();
  //       } else if (props.followType === 'fans') {
  //         loadFans();
  //       }
  //     } else {
  //       // 弹窗隐藏时移除滚动监听
  //       removeScrollListener();
  //     }
  //   },
  //   { immediate: true }
  // );

  // 生命周期
  onMounted(() => {
    // 如果弹窗已经显示，添加滚动监听
    if (props.showFollowModal) {
      addScrollListener();
    }
  });

  onUnmounted(() => {
    // 移除滚动监听
    removeScrollListener();
  });
</script>

<style scoped lang="scss">
  .modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    animation: fadeIn 0.3s ease;
  }

  .modal-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
    padding: 24px;
    max-width: 560px;
    width: 90%;
    height: 720px;
    display: flex;
    flex-direction: column;
    animation: slideIn 0.3s ease;
  }

  .tab-container {
    display: flex;
    justify-content: center;
    gap: 40px;
  }

  .tab-item {
    display: flex;
    align-items: center;
    gap: 4px;
    padding: 12px 0px;
    cursor: pointer;
    color: #7a7a7a;
    font-weight: 500;

    &.active {
      border-bottom: 2px solid #f76b1b;
      color: #222;
    }

    &:hover:not(.active):not(.disabled) {
      color: #222;
    }

    &.disabled {
      cursor: not-allowed;
      opacity: 0.5;
      color: #ccc;
    }
  }

  .search-filter-container {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 0;
    border-bottom: 1px solid #e1e2e3;
  }

  .search-input-wrapper {
    position: relative;
    flex: 1;
  }

  .search-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #7a7a7a;
    pointer-events: none;
  }

  .search-input {
    width: 100%;
    height: 40px;
    padding: 8px 12px 8px 36px;
    border-radius: 8px;
    font-size: 14px;
    background: #f8f8f8;
    transition: all 0.2s ease;

    &:focus {
      outline: none;
      border-color: none;
    }

    &::placeholder {
      color: #7a7a7a;
    }
  }

  .filter-wrapper {
    flex-shrink: 0;
  }

  .filter-button {
    display: flex;
    align-items: center;
    gap: 6px;
    padding: 8px 12px;
    border: 1px solid #e1e2e3;
    border-radius: 8px;
    background: white;
    color: #7a7a7a;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      border-color: #f76b1b;
      color: #f76b1b;
    }
  }

  .filter-content {
    padding: 8px 0;
  }

  .filter-item {
    padding: 8px 16px;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      background: #f8f8f8;
    }

    span {
      font-size: 14px;
      color: #7a7a7a;

      &.active {
        color: #f76b1b;
        font-weight: 500;
      }
    }
  }

  .user-list {
    flex: 1;
    overflow-y: auto;
  }

  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    color: #7a7a7a;
    gap: 12px;
  }

  .loading-spinner {
    width: 24px;
    height: 24px;
    border: 2px solid #e1e2e3;
    border-top: 2px solid #f76b1b;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  .empty-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    height: 100%;
    padding: 40px 0;
    color: #7a7a7a;
    gap: 12px;
  }

  .empty-icon {
    font-size: 32px;
  }

  .load-more-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
    color: #7a7a7a;
    gap: 8px;
  }

  .no-more-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
    margin-top: auto;
    font-style: 14px;
    color: #7a7a7a;
  }

  .no-more-text {
    padding: 4px 0px;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    color: #a7a7a7;
    font-size: 16px;
    font-weight: 500;
    text-align: center;
  }

  .user-items {
    display: flex;
    flex-direction: column;
    gap: 8px;
    height: 100%;
  }

  .user-item {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 16px 0px;
    border-radius: 8px;
    transition: all 0.2s ease;
  }

  .user-avatar {
    flex-shrink: 0;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .user-info {
    flex: 1;
    min-width: 0;
  }

  .user-name {
    font-size: 16px;
    font-weight: 500;
    color: #222;
  }

  .user-meta {
    font-size: 12px;
    color: #7a7a7a;
  }

  .user-actions {
    flex-shrink: 0;
  }

  .follow-button {
    padding: 6px 16px;
    border-radius: 8px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100px;

    &:disabled {
      cursor: not-allowed;
      opacity: 0.6;
    }

    &.follow {
      background: #f76b1b;
      color: white;

      &:hover:not(:disabled) {
        background: #e55a0f;
      }
    }

    &.following {
      color: #222;
      background: #ededed;

      &:hover:not(:disabled) {
        background: #f8f8f8;
      }
    }
  }

  .button-loading {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .mini-spinner {
    width: 12px;
    height: 12px;
    border: 2px solid transparent;
    border-top: 2px solid currentColor;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  // 动画效果
  @keyframes fadeIn {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
  }

  @keyframes slideIn {
    from {
      opacity: 0;
      transform: translateY(-20px) scale(0.95);
    }
    to {
      opacity: 1;
      transform: translateY(0) scale(1);
    }
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>
